package com.tele.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.tele.domain.User;
import com.tele.domain.UserLoginVo;
import com.tele.service.ints.LoginService;
import com.tele.utils.ConstantPropertiesUtil;
import com.tele.utils.HttpClientUtils;
import com.tele.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/weixin")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/wxLogin/{code}")
    public R callback(@PathVariable String code) {
        //为空返回空信息
        if (StringUtils.isEmpty(code)) {
            return R.fail("code 为空！");
        }
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
            .append("https://api.weixin.qq.com/sns/jscode2session")
            .append("?appid=%s")
            .append("&secret=%s")
            .append("&js_code=%s")
            .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
            ConstantPropertiesUtil.WX_OPEN_APP_ID,
            ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
            code);

        String res = null;
        try {
            res = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println("使用code换取的access_token结果 = " + res);

        //转成json获取id和密钥
        JSONObject resultJson = JSONObject.parseObject(res);
        if (resultJson.getString("errcode") != null) {
            throw new RuntimeException("获取accessToken失败");
        }

        //得到key和openid
        String accessToken = resultJson.getString("session_key");
        String openId = resultJson.getString("openid");
        //根据access_token获取微信用户的基本信息
        //先根据openid进行数据库查询
//        System.out.println("oprnid " + openId);
        User user = loginService.getByOpenid(openId);
//        System.out.println("user " + user);
        // 如果没有查到用户信息,那么调用微信个人信息获取的接口
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            user.setNickName(openId);
            user.setPhotoUrl("");
            loginService.save(user);
        }
        //将信息存入redis
        Map<String, Object> map = new HashMap<>();

        String token = JwtHelper.createToken(user.getId(), user.getNickName());

        StpUtil.login(user.getId());
        String sa_token = StpUtil.getTokenValue();
        System.out.println("sa_token" + sa_token);
        map.put("user", user);
        map.put("token", token);
        map.put("sa_token", sa_token);
        //得到用户登录信息
        UserLoginVo userLoginVo = loginService.getUserLoginVo(user.getId());

        //Sa-Token login
//        System.out.println(StpUtil.getTokenValue());
//        StpUtil.setTokenValue(token);
//        System.out.println(StpUtil.getTokenValue());


        redisTemplate.opsForValue().set("user:login:" + user.getId(), userLoginVo, 7, TimeUnit.DAYS);
        return R.ok(map);
    }

    //更新用户头像和名称
    @PostMapping("/auth/updateUser")
    public R updateUser(@RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("token");

        if (!StringUtils.isEmpty(token)) {
            Long userId = JwtHelper.getUserId(token);
            System.out.println(userId);
            User user1 = loginService.getBaseMapper().selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, userId));
            System.out.println(user1);
            //把昵称更新为微信用户
            if (user1 != null) {
                user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
                user1.setPhotoUrl(user.getPhotoUrl());
                loginService.updateById(user1);

            }
        }
        return R.ok();
    }
}
